package ict.kth.se.web;

import java.util.ArrayList;
import java.util.List;

import ict.kth.se.manager.CookieManager;
import ict.kth.se.manager.PersonManager;
import ict.kth.se.manager.SeekerManager;
import ict.kth.se.model.Competence;
import ict.kth.se.model.Person;
import ict.kth.se.model.Role;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

/**
 * Handles requests for the application home page.
 */
@Controller
public class AdminController {

	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	private SeekerManager seekerManager;
	private PersonManager personManager;
	
	/**
	 * public constructor
	 * @param seekerManager seekermanager to be set
	 * @param personManager personmanager to be set
	 */
	@Autowired
	public AdminController(SeekerManager seekerManager, PersonManager personManager) {
		this.seekerManager = seekerManager;
		this.personManager = personManager;
	}
	
	/**
	 * openAdminPage, map to /moel
	 * @param language language set
	 * @param request HTTPServletRequest
	 * @param response HTTPServletResponse
	 * @return modelandview
	 */
	@RequestMapping(value = "admin", method = RequestMethod.GET)
	public ModelAndView openAdminPage(@RequestParam(value="language", required=false) String language,
			HttpServletRequest request, HttpServletResponse response) {
		try{
			//Create modelAndView to be sent to view
			ModelAndView modelAndView = new ModelAndView("adminPage");
			//Language
			modelAndView = CookieManager.handleLanguageCookie(modelAndView, request, response, language);
			
			modelAndView.addObject("allSeekers", seekerManager.getAllSeekers());
			
			modelAndView.addObject("allRecruiters", personManager.getAllRecruiters());
			
			return modelAndView;
		}
		catch(Exception e){
			e.printStackTrace();
			//Create modelAndView to be sent to view for errors
			ModelAndView modelAndView = new ModelAndView("error");
			modelAndView.addObject("error", e.getMessage());
			return modelAndView;
		}
	}
	
	/**
	 * createNewUser, creates new user
	 * @param language the chosen language
	 * @param request HTTPServletRequest
	 * @param response HTTPServletResponse
	 * @return returns model and view
	 * @throws Exception if something went wrong
	 */
	@RequestMapping("createNewUser")
	public ModelAndView createNewUser(@RequestParam(value="language", required=false) String language,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		try{
			ModelAndView modelAndView	=	new ModelAndView("newUserForm");
			modelAndView	=	CookieManager.handleLanguageCookie(modelAndView, request, response, language);
			return modelAndView;
		}
		catch(Exception e){
			e.printStackTrace();
			//Create modelAndView to be sent to view for errors
			ModelAndView modelAndView = new ModelAndView("error");
			modelAndView.addObject("error", e.getMessage());
			return modelAndView;
		}
	}
	
	/**
	 * insertNewUser 
	 * @param firstName persons firstname
	 * @param lastName persons lastname
	 * @param email persons email
	 * @param ssn persons social security number
	 * @param username person username
	 * @param password person password
	 * @param language chosen language
	 * @param request HTTPServletRequest
	 * @param response HTTPServletResponse
	 * @return modelandview
	 * @throws Exception if something went wrong
	 */
	@RequestMapping("insertNewUser")
	public ModelAndView insertNewUser(
			@RequestParam("firstName") String firstName, 
			@RequestParam("lastName") String lastName,  
			@RequestParam("email") String email, 
			@RequestParam("ssn") String ssn,
			@RequestParam("username") String username,
			@RequestParam("password") String password,
			@RequestParam(value="language", required=false) String language,
			HttpServletRequest request, 
			HttpServletResponse response) throws Exception {
		
		try{
			ModelAndView modelAndView	=	new ModelAndView("adminPage");
			modelAndView	=	CookieManager.handleLanguageCookie(modelAndView, request, response, language);
		
			//Encrypts password
			Md5PasswordEncoder encoder = new Md5PasswordEncoder();
			String encryptedPass = encoder.encodePassword("admin", Person.PASSWORD_ENCRYPT_SALT);
		
			List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
			authList.add(new GrantedAuthorityImpl(Role.ROLE_RECRUITER));		
			Person person = new Person(firstName, lastName, ssn, email, username, encryptedPass, true, authList);
		
			Role role = new Role();
			role.setName(Role.ROLE_RECRUITER);
			person.setRole(role);
		
			person = personManager.createNewUser(person);
		
			//modelAndView.addObject("person", person);
			modelAndView.addObject("allSeekers", seekerManager.getAllSeekers());
			modelAndView.addObject("allRecruiters", personManager.getAllRecruiters());
		
			return modelAndView;
		}
		catch(Exception e){
			e.printStackTrace();
			//Create modelAndView to be sent to view for errors
			ModelAndView modelAndView = new ModelAndView("error");
			modelAndView.addObject("error", e.getMessage());
			return modelAndView;
		}
	}
	
	/**
	 * getAdminById
	 * @param personId persons id
	 * @param language chosen language
	 * @param request HTTPServletRequest
	 * @param response HTTPServletResponse
	 * @return modelandview
	 */
	@RequestMapping(value = "adminDetails")
	public ModelAndView getAdminById(
			@RequestParam("id") Long personId,
			@RequestParam(value="language", required=false) String language,
			HttpServletRequest request, HttpServletResponse response) {
		try{
			//Create modelAndView to be sent to view
			ModelAndView modelAndView = new ModelAndView("adminDetails");
			//Language
			modelAndView = CookieManager.handleLanguageCookie(modelAndView, request, response, language);
			
			modelAndView.addObject("person", personManager.getPersonById(personId));
			
			return modelAndView;
		}
		catch(Exception e){
			e.printStackTrace();
			//Create modelAndView to be sent to view for errors
			ModelAndView modelAndView = new ModelAndView("error");
			modelAndView.addObject("error", e.getMessage());
			return modelAndView;
		}
	}
}
